//
//  DownloadView.m
//  handbooklite
//
//  Created by bao_wsfk on 12-8-29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DownloadView.h"
#import "QRCodeReader.h"
#import "NSString_NSString.h"
#import "JSONKit.h"
#import "DownNumFileUtil.h"

@interface DownloadView ()

@end

@implementation DownloadView

@synthesize tfDownNum =_tfDownNum;
@synthesize bookCell =_bookCell;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title =@"下载";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.tfDownNum =nil;
    self.bookCell =nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return [self orientationByString:ORIENTATION InterfaceOrientation:interfaceOrientation];
}

//点击拍照按钮
- (void)scanClickSelector:(id)sender{
    ZXingWidgetController *widController = [[ZXingWidgetController alloc] initWithDelegate:self showCancel:YES OneDMode:NO];
    QRCodeReader* qrcodeReader = [[QRCodeReader alloc] init];
    NSSet *readers = [[NSSet alloc ] initWithObjects:qrcodeReader,nil];
    [qrcodeReader release]; 
    widController.readers = readers;
    [readers release];
    NSBundle *mainBundle = [NSBundle mainBundle];
    //声音播放
    widController.soundToPlay =
    [NSURL fileURLWithPath:[mainBundle pathForResource:@"beep-beep" ofType:@"aiff"] isDirectory:NO];
    [self presentModalViewController:widController animated:YES];
    [widController release];
}

#pragma mark-ZXingDelegate
- (void)zxingControllerDidCancel:(ZXingWidgetController *)controller{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark-ZXingDelegate
- (void)zxingController:(ZXingWidgetController *)controller didScanResult:(NSString *)result{
    if (self.isViewLoaded) {
        [_tfDownNum setText:result];
    }
    [self dismissModalViewControllerAnimated:NO];
}

- (void)commitSelector:(id)sender{
    NSString *downNum =[_tfDownNum text];
    CCLog(@"------downnum:%@",downNum);
    if (downNum ==nil || [downNum isEmpty]) {
        [self showMessage:@"请输入下载码"];
        return;
    }
    //判断downnum.json是否存在 并且下载码是否存在
    DownNumFileUtil *dfu =[DownNumFileUtil newInstance];
    if ([dfu isHasDownNum:[_tfDownNum text]]) {
        [self showMessage:@"您已经下载过这本手册了"];
        return;
    }
    
    ASIFormDataRequest *request =[ASIFormDataRequest
                                  requestWithURL:[NSURL URLWithString:DOWNLOAD_URL]];
    [request setDelegate:self];
    //不再重用上一个url
    [request setShouldAttemptPersistentConnection:NO];
    [request setTimeOutSeconds:10];
    [request setPostValue:[_tfDownNum text] forKey:@"downloadnum"];
    [request startAsynchronous];
    _waitAlert =[[CustomAlertView alloc] initWaitAlert:@"请稍等..."
                                               message:@"正在请求数据"
                                              delegate:self];
    [_waitAlert show];
}

#pragma mark -ASIHTTPRequestDelegate

- (void)requestFailed:(ASIHTTPRequest *)request{
    [_waitAlert dismiss];
    _waitAlert =nil;
    [self showMessage:@"由于网络错误，请重新操作"];
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    [_waitAlert dismiss];
    _waitAlert =nil;
    
    //解析{"status":"success","error":"null","book":{"name":"时尚家居展览会201208版","icon":"icon/icon.png","zip":"zip/123.zip"}}
    if ([request responseStatusCode] ==200) {
        NSDictionary *data = [(NSDictionary *)[[request responseData] objectFromJSONData]
                              objectForKey:@"handbookMsg"];
        //CCLog(@"------data:%@",data);
        //供测试使用
//        NSString *d =@"{\"status\":\"success\",\"error\":\"null\",\"book\":{\"name\":\"时尚家居展览会201208版\",\"icon\":\"icon/icon.jpg\",\"zip\":\"zip/book1.zip\"}}";
//        data =[d objectFromJSONString];
        //return;
        if ([@"success" isEqualToString:[data objectForKey:@"status"]]) {
            
            NSMutableDictionary *book =[[data objectForKey:@"book"] mutableCopy];
            [book setObject:[_tfDownNum text] forKey:@"downnum"];
            [book setObject:_bookCell forKey:@"bookcell"];
            [self.navigationController popViewControllerAnimated:YES];
            //通知下载
            [[NSNotificationCenter defaultCenter] postNotificationName:@"download"
                                                                object:book];
        }
        else {
            [self showMessage:[data objectForKey:@"error"]];
        }
        
    }else {
        [self showMessage:[NSString stringWithFormat:@"请求错误:%i",[request responseStatusCode]]];
    }
}
@end
